package edu.cmu.ibill.databeans;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * Bean Class for User Table.
 * 
 * @author Yunkai Zhang
 */

public class User {

	private int id = -1;
	private String emailAddress = null;
	private String firstname = null;
	private String lastname = null;
	private int salt = 0;
	private String hashedPassword = null;

	public User() {
		;
	}

	public User(int id) {
		this.id = id;
	}

	public User(String email) {
		if (email != null)
			this.emailAddress = email.trim();
	}

	public int getSalt() {
		return salt;
	}

	public String getUserName() {
		return firstname + " " + lastname;
	}

	public int getId() {
		return id;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public String getFirstname() {
		return firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public String getHashedPassword() {
		return hashedPassword;
	}

	public int hashCode() {
		return (emailAddress).hashCode();
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setSalt(int salt) {
		this.salt = salt;
	}

	public void setEmailAddress(String email) {
		this.emailAddress = email;
	}

	public void setFirstname(String first) {
		this.firstname = first;
	}

	public void setLastname(String last) {
		this.lastname = last;
	}

	public void setPassword(String pw) {
		salt = newSalt();
		hashedPassword = hash(pw);
	}

	public void setHashedPassword(String hpw) {
		hashedPassword = hpw;
	}

	public String toHash(String s) {
		return hash(s);
	}

	/**
	 * Hash the clearpassword into a hashed code
	 * 
	 * @param clearPassword
	 * @return
	 */
	private String hash(String clearPassword) {
		if (salt == 0)
			return null;

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA1");
		} catch (NoSuchAlgorithmException e) {
			throw new AssertionError(
					"Can't find the SHA1 algorithm in the java.security package");
		}

		String saltString = String.valueOf(salt);

		md.update(saltString.getBytes());
		md.update(clearPassword.getBytes());
		byte[] digestBytes = md.digest();

		// Format the digest as a String
		StringBuffer digestSB = new StringBuffer();
		for (int i = 0; i < digestBytes.length; i++) {
			int lowNibble = digestBytes[i] & 0x0f;
			int highNibble = (digestBytes[i] >> 4) & 0x0f;
			digestSB.append(Integer.toHexString(highNibble));
			digestSB.append(Integer.toHexString(lowNibble));
		}
		String digestStr = digestSB.toString();

		return digestStr;
	}

	public int salt() {
		return salt;
	}

	/**
	 * Generate Random Number for salt.
	 * 
	 * @return
	 */
	private int newSalt() {
		Random random = new Random();
		return random.nextInt(8192) + 1;
	}

	public String toString() {
		return lastname + " " + firstname;
	}

	public boolean checkPassword(String password) {
		return hashedPassword.equals(hash(password));
	}
}
